/**
 * Created by xstnet on 2018/7/3.
 * Author: xstnet
 */
import React from 'react';
import { connect } from 'react-redux'
import { Table, Button, Switch, Modal, Form, Input, Icon, Popconfirm, Tree } from 'antd';
import { getRoles, changeRoleStatus, saveRoles, deleteRoles, getPermissionTree, getRolePermission, setRolePermission } from '@/api/Api.js'
import {getFormItemLayout} from "../../utils/CommonUtil";

const FormItem = Form.Item;
const TreeNode = Tree.TreeNode;
const formItemLayout = getFormItemLayout(24, 4, 24, 19);

const mapStateToProps = (state, ownProps) => ({
	roles: state.Permission.roles,
	config: state.common.config,
})

// rowSelection object indicates the need for row selection
const rowSelection = {
	onChange: (selectedRowKeys, selectedRows) => {
		console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
	},
};
const ADD_TITLE = <span className='modal-title'><Icon type='plus'/> 添加角色</span>
const EDIT_TITLE = <span className='modal-title'><Icon type='edit'/> 编辑角色</span>

class Role extends React.Component {
	constructor(props) {
		super(props);
	}
	state = {
		loading: true,
		visible: false,
		actionTitle: ADD_TITLE,
		actionType: '',
		editIndex: '',
		permissionTree: [],
		permissionVisible: false,
		checkedPermissions: [],
		currentRoleId: [],
	}

	columns = [
		{ title: 'ID', dataIndex: 'id', },
		{ title: '名称', dataIndex: 'name', },
		{ title: '描述', dataIndex: 'description', },
		{ title: '排序', dataIndex: 'sort_value', },
		{ title: '添加时间', dataIndex: 'created_at', },
		{
			title: '状态',
			align: 'center',
			dataIndex: 'status',
			width: 100,
			render: (text, record, index) => {
				return(<Switch onChange={this.handleChangeStatus.bind(this, record, index)} checked={parseInt(record.status) === 0} checkedChildren="启用" unCheckedChildren="禁用" />)
			},
		}, {
			title: '操作',
			align: 'center',
			key: 'operation',
			width: 280,
			render: (text, record, index) => {
				return (<span>
					<Button type="success" style={{marginRight: 10}} onClick={this.onSetPermission.bind(this, record, index)} icon="lock" size='small'>设置权限</Button>
					<Button type="primary" style={{marginRight: 10}} onClick={this.onEdit.bind(this, record, index)} icon="edit" size='small'>编辑</Button>
					<Popconfirm title="确定要删除这个角色吗?" okText="确定" onConfirm={this.onDelete.bind(this, record.id, index)} cancelText="取消">
						<Button type="danger" size='small' icon="delete" htmlType="button">删除</Button>
					</Popconfirm>
				</span>)
			},
		},
	];

	handleChangeStatus = (record, index, checked,) => {
		changeRoleStatus(record, index, checked).then(result => {
		})
	}

	/**
	 * 点击添加 响应
	 */
	onAdd = () => {
		this.props.form.resetFields();
		this.setState({
			visible: true,
			actionTitle: ADD_TITLE,
			actionType: 'add',
		});
	}
	/**
	 * 点击编辑 响应
	 */
	onEdit = (item, index) => {
		console.log(item)
		this.props.form.resetFields();
		this.setState({
			visible: true,
			actionTitle: EDIT_TITLE,
			actionType: 'save',
			editIndex: index,
		});
		this.props.form.setFieldsValue(item);
	}

	onDelete = (id, index) => {
		deleteRoles(id, index)
	}

	/**
	 * 打开设置权限modal
	 * @param item
	 * @param index
	 */
	onSetPermission = (item, index) => {
		if (this.state.permissionTree == false) {
			getPermissionTree().then(result => {
				if (result) {
					this.setState({permissionTree: result.result})
				}
			})
		}
		getRolePermission(item.id).then(result => {
			console.log(result, 777);
			if (result) {
				this.setState({
					checkedPermissions: {checked: result.result},
					permissionVisible: true,
					currentRoleId: item.id,
				})
			}
		})
	}

	/**
	 * 设置权限
	 */
	handleSetPermission = () => {
		let permissions;
		if (this.state.checkedPermissions.checked) {
			permissions = this.state.checkedPermissions.checked;
		} else {
			permissions = [];
		}
		setRolePermission(this.state.currentRoleId, permissions).then(res => {
			if (res) {
				this.setState({permissionVisible: false});
			}
		})
	}

	handleSave = (e) => {
		e.preventDefault();
		this.props.form.validateFieldsAndScroll((err, values) => {
			if (err) {
				console.log(err);
				return false;
			}
			saveRoles(this.state.actionType, values, this.state.editIndex).then(code => {
				if (code === 0) {
					this.setState({
						visible: false,
					});
				}
			});
		})
	}

	renderTreeNodes = (data) => {
		return data.map((item) => {
			if (item.children) {
				return (
					<TreeNode {...item}>
						{this.renderTreeNodes(item.children)}
					</TreeNode>
				);
			}
			item.value = item.key;
			return <TreeNode {...item} />;
		});
	}

	handleCancel = (e) => {
		this.setState({
			visible: false,
			permissionVisible: false,
		});
	}

	onCheck = (checkedKeys, info) => {
		this.setState({checkedPermissions: checkedKeys});
		console.log('onCheck1', checkedKeys);
	}

	componentDidMount() {
		getRoles().then(res => {
			this.setState({loading: false})
		})
	}
	render() {
		const { getFieldDecorator } = this.props.form;
		return (
			<div>
				<Button onClick={this.onAdd} icon='plus' type="primary" style={{ marginBottom: 16, marginRight:16 }}>添加</Button>
				<Button onClick={this.handleDelete} type="danger" icon='delete' style={{ marginBottom: 16 }}>删除</Button>
				<Table className='bg-white' rowSelection={rowSelection} bordered size='small' columns={this.columns} dataSource={this.props.roles}
					   title={() => '角色列表'}
					   rowKey="id"
					   loading={this.state.loading}
				/>
				<div>
					<Modal
						title={this.state.actionTitle}
						visible={this.state.visible}
						onOk={this.handleSave}
						onCancel={this.handleCancel}
						okText="保存"
						width={660}
						cancelText="取消"
					>
						<Form>
							<FormItem {...formItemLayout} label="名称">
								{getFieldDecorator('name', {
									rules: [{
										required: true, message: '请输入名称',},
									],
								})(<Input />)}
							</FormItem>
							<FormItem {...formItemLayout} label="描述">
								{getFieldDecorator('description', {
									initialValue: '',
								})(<Input />)}
							</FormItem>
							<FormItem {...formItemLayout} label="排序">
								{getFieldDecorator('sort_value', {
									initialValue: '100',
								})(<Input placeholder='100' />)}
							</FormItem>
							<span>
								{getFieldDecorator('id', {
									initialValue: '0',
								})(<Input type='hidden' />)}
							</span>
						</Form>
					</Modal>
				</div>
				<div>
					<Modal
						title='设置权限'
						visible={this.state.permissionVisible}
						onOk={this.handleSetPermission}
						onCancel={this.handleCancel}
						okText="保存"
						width={660}
						cancelText="取消"
					>
						<Tree
							checkable
							checkedKeys={this.state.checkedPermissions}
							checkStrictly
							onCheck={this.onCheck}
							// selectedKeys={this.state.selectedKeys}
						>
							{this.renderTreeNodes(this.state.permissionTree)}
						</Tree>
					</Modal>
				</div>
			</div>
		)
	}
}

export default connect(
	mapStateToProps,
)(Form.create()(Role))